package com.magicodex.bookkeeping.ui.statistic;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.magicodex.bookkeeping.biz.statistic.constant.StatisticConstants;
import com.magicodex.bookkeeping.biz.statistic.dto.StatisticDTO;
import com.magicodex.bookkeeping.biz.statistic.event.SettingFabClickListener;
import com.magicodex.bookkeeping.biz.statistic.event.StatisticItemClickListener;
import com.magicodex.bookkeeping.biz.statistic.util.StatisticDataUtil;
import com.magicodex.bookkeeping.databinding.FragmentStatisticBinding;

import java.util.ArrayList;
import java.util.List;

public class StatisticFragment extends Fragment {

    private FragmentStatisticBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        StatisticViewModel statisticViewModel =
                new ViewModelProvider(this).get(StatisticViewModel.class);

        binding = FragmentStatisticBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        Activity activity = getActivity();
        ListView listView = binding.statisticList;
        FloatingActionButton settingButton = binding.fabSetting;

        // 统计列表
        List<StatisticDTO> recordList = new ArrayList<>(loadData());
        StatisticListViewAdapter adapter = new StatisticListViewAdapter(activity, recordList);
        listView.setAdapter(adapter);

        // 监听事件
        listView.setOnItemClickListener(new StatisticItemClickListener(activity, adapter));
        settingButton.setOnClickListener(new SettingFabClickListener(activity, adapter));

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    /**
     * 加载数据
     *
     * @return
     */
    protected List<StatisticDTO> loadData() {
        Context context = getContext();
        List<StatisticDTO> recordList = StatisticDataUtil.loadStatisticRecords(context,
                StatisticConstants.ACCOUNT_CATEGORY_START_SYMBOL_DEFAULT,
                StatisticConstants.ACCOUNT_CATEGORY_END_SYMBOL_DEFAULT);

        return recordList;
    }

}
